<template>
  <div class="wrapper" ref="wrapper">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
  import BScroll from "better-scroll"

  export default {
    name: "BScroll",
    props: {
      probeType: {
        type: Number,
        default: 0
      },
      pullUpLoad: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        scroll: null
      }
    },
    mounted() {
      setTimeout(() => {
        //1、创建BScroll对象
        //通过document.querySelector()获取的元素不够准确，在Vue中通过给元素绑定ref的方式更准确
        this.scroll = new BScroll(this.$refs.wrapper, {
          click: true,
          probeType: this.probeType,
          pullUpLoad: this.pullUpLoad
        })
        // console.log(this.scroll);//输出的结果中scrollHeight决定了可滚动区域的高度

        //2、监听滚动的位置
        if (this.probeType === 2 || this.probeType ===3) {
          this.scroll.on('scroll', (position) => {
            // console.log(position);
            //将自定义事件发出去
            this.$emit('scroll', position)
          })
        }

        //3、监听上拉加载更多事件(scroll滚动到底部)
        if (this.pullUpLoad) {
          this.scroll.on('pullingUp', () => {
            this.$emit('pullingUp')
          })
        }



      },1000)
    },
    methods: {
      scrollTo(x, y, time=500) {
        //在this.scroll有值的情况下再去做后面的事
        this.scroll && this.scroll.scrollTo(x, y, time)
      },
      finishPullUp() {
        this.scroll && this.scroll.finishPullUp()
      },
      refresh() {
        this.scroll && this.scroll.refresh()
      },
      getScrollY() {
        return this.scroll ? this.scroll.y : 0
      }
    }
  }
</script>

<style scoped>
  .wrapper {
    touch-action: none;
  }
</style>
